package com.nice.nice201110.service;

import com.nice.nice201110.entity.SysQuartz;
import com.nice.nice201110.mapper.SysQuartzMapper;
import com.nice.nice201110.vo.BaseVo;
import com.nice.nice201110.vo.UserVo;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class SysQuartzService {

    @Autowired
    SysQuartzMapper sysQuartzMapper;

    @Autowired
    private Scheduler scheduler;

    protected Logger log = LoggerFactory.getLogger(this.getClass());
    /**
     *  查询定时任务(执行任务)
     * */
    public List<SysQuartz> selectAllStatus() {
        return sysQuartzMapper.selectByStatus();
    }
    /**
     *  查询定时任务s
     * */
    public List<SysQuartz> selectAll(BaseVo basevo) {
        return sysQuartzMapper.selectByPrimaryKeys(basevo);
    }
    /**
     * 添加定时任务
     */
    public Boolean add(UserVo userVo, SysQuartz sysQuartz) {
        sysQuartz.setCreateTime(new Date());
        sysQuartz.setCreateUser(Long.getLong(userVo.getId()));
        sysQuartz.setDelFlag(false);
        sysQuartzMapper.insertSelective(sysQuartz);
        // 启动
        if ("0"==sysQuartz.getQuartzStatus()) {
            this.schedulerAdd(sysQuartz.getClassName().trim(), sysQuartz.getCronExpression().trim(), sysQuartz.getParam());
        }
        return true;
    }
    /**
     * 更新定时任务
     */
    public Boolean update(SysQuartz sysQuartz) {
        sysQuartzMapper.updateByPrimaryKeySelective(sysQuartz);
        // 启动
        if ("0"==sysQuartz.getQuartzStatus()) {
            String className = sysQuartz.getClassName();
            this.schedulerDelete(className);
            this.schedulerAdd(className, sysQuartz.getCronExpression().trim(), sysQuartz.getParam());
        }else{
            String className = sysQuartz.getClassName();
            try {
                scheduler.pauseTrigger(TriggerKey.triggerKey(className));
                scheduler.unscheduleJob(TriggerKey.triggerKey(className));
                scheduler.deleteJob(JobKey.jobKey(className));
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }
        return true;
    }
    /**
     *  删除定时任务
     */
    public Boolean delete(UserVo userVo, long id) {
        SysQuartz sysQuartz = sysQuartzMapper.selectByPrimaryKey(id);
        if(sysQuartz!=null){
            String className = sysQuartz.getClassName();
            sysQuartz.setDelFlag(true);
            sysQuartzMapper.updateByPrimaryKeySelective(sysQuartz);
            try {
                scheduler.pauseTrigger(TriggerKey.triggerKey(className));
                scheduler.unscheduleJob(TriggerKey.triggerKey(className));
                scheduler.deleteJob(JobKey.jobKey(className));
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }
        return false;
    }

    /**
     * 添加定时任务
     *
     * @param className
     * @param cronExpression
     * @param param
     */
    public void schedulerAdd(String className, String cronExpression, String param) {
        try {
            // 启动调度器
            scheduler.start();
            // 构建job信息
            JobDetail jobDetail = JobBuilder.newJob(getClass(className).getClass()).withIdentity(className).usingJobData("param", param).build();
            // 表达式调度构建器(即任务执行的时间)
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cronExpression);
            // 按新的cronExpression表达式构建一个新的trigger
            CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(className).withSchedule(scheduleBuilder).build();
            scheduler.scheduleJob(jobDetail, trigger);
        } catch (SchedulerException e) {
            log.error(e.getMessage());
        } catch (RuntimeException e) {
            log.error(e.getMessage());
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }

    /**
     * 删除定时任务
     *
     * @param className
     */
    public void schedulerDelete(String className) {
        try {
            scheduler.pauseTrigger(TriggerKey.triggerKey(className));
            scheduler.unscheduleJob(TriggerKey.triggerKey(className));
            scheduler.deleteJob(JobKey.jobKey(className));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
    private static Job getClass(String className) throws Exception {
        Class<?> class1 = Class.forName(className);
        return (Job) class1.newInstance();
    }
}
